package com.vma.user.service;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.vma.neng.tools.AppException;
import com.vma.shoes.bizModel.model.*;
import com.vma.user.vo.SmsCode;

import java.sql.SQLException;
import java.util.*;

/**
 * Created by chenzui on 2017/4/11.
 */
public class UserService {
    public static Page<User> qryUserList(Integer cPage, Integer pSize, String status, String phone, String start, String end){
        String condition = "";
        List<String> param = new ArrayList<String>();
        if(status != null && !"".equals(status)){
            condition += "and status = ? ";
            param.add(status);

        }
        if(start != null && !"".equals(start)){
            condition += "and create_time > ? ";
            param.add(start);
        }
        if(end != null && !"".equals(end)){
            condition += "and create_time < ? ";
            param.add(end);
        }
        if(phone != null && !"".equals(phone)){
            condition += "and phone like ? ";
            param.add("%"+phone+"%");
        }
        Page<User> users = User.dao.paginate(cPage,pSize,"SELECT\n" +
                        "  u.id,\n" +
                        "  u.name,\n" +
                        "  u.status,\n" +
                        "  u.phone,\n" +
                        "  uei.last_buy_time,\n" +
                        "  uei.last_login_time,\n" +
                        "  uei.total_order_cnt,\n" +
                        "  uei.total_order_price","FROM user u, user_ext_info uei\n" +
                        "WHERE u.id = uei.user_id "+condition+" order by u.id desc"
                ,param.toArray());


        return users;
    }

    public static Map loginByPwd(String phone,String password){
        Map result = new HashMap();
        //1 先查手机号 2匹配密码
        List<User> users = User.dao.find("select * from user where phone = ? ",phone);
        if(users != null && users.size() > 0){
            User user = users.get(0);
            if(user.getStatus().equals("1")){
                UserPwd userPwd = UserPwd.dao.findFirst("SELECT * FROM user_pwd WHERE user_id = ? ORDER BY create_time DESC",user.getId());
                if(password.equals(userPwd.getPassword())){
                    result.put("resultCode","0");
                    result.put("userId",user.getId());
                    UserExtInfo userExtInfo = UserExtInfo.dao.findFirst("SELECT * FROM user_ext_info WHERE user_id = ?",user.getId());
                    userExtInfo.setLastLoginTime(new Date()).update();
                    new UserLogin().setUserId(user.getId()).setCreateTime(new Date()).save();
                }else {
                    result.put("resultCode","-1");
                    result.put("resultMsg","error password");
                }
            }else {
                result.put("resultCode","-2");
                result.put("resultMsg","用户被禁止登录");
            }


        }else {
            result.put("resultCode","-1");
            result.put("resultMsg","no users find");
        }
        return result;
    }

    public static Integer login3rd(String openId){
        User user = User.dao.findFirst("SELECT * FROM user WHERE wx_open_id = ?",openId);
        if(user == null){
            user = new User().setStatus("1").setCreateTime(new Date()).setWxOpenId(openId);
            user.save();
        }
        if("0".equals(user.getStatus())){
            throw new AppException("-1","用户被禁用");
        }
        return user.getId();
    }

    public static Map signUp( String phone, String password,String smsMessageSid,String smsCode){
        Map result = new HashMap();
        final Date date = new Date();

        List<MessageLogs> list = MessageLogs.dao.find("SELECT * FROM message_logs WHERE sms_message_sid = ?",smsMessageSid);
        if(list != null && list.size() != 0){
            MessageLogs log = list.get(0);
            if("-1".equals(log.getSTATUS())){
                result.put("errorInfo","验证码已使用");
                result.put("errorCode","-1");
            }
            if(!log.getCODE().equals(smsCode)){
                result.put("errorInfo","验证码错误");
                result.put("errorCode","-2");
            }else if(!log.getPHONE().equals(phone)){
                result.put("errorInfo","电话号码不匹配");
                result.put("errorCode","-3");
            }else if(new Date().getTime() - Long.valueOf(log.getCreateTime()) > 1000*60*5){
                result.put("errorInfo","验证码超时");
                result.put("errorCode","-4");
            }else {
                log.setSTATUS("-1").update();
                List<User> users = User.dao.find("SELECT * FROM user where phone = ?",phone);
                if(users != null && users.size() != 0){
                    result.put("errorInfo","用户已存在");
                    result.put("errorCode","-5");
                }else {
                    User user = new User();
                    user.setPhone(phone).setStatus("1").setCreateTime(date).save();
                    UserPwd pwd = new UserPwd();
                    pwd.setCreateTime(date).setPassword(password).setUserId(user.getId()).save();


                    new UserExtInfo().setLastLoginTime(new Date()).setTotalOrderCnt(0).setTotalOrderPrice(0F).setUserId(user.getId()).save();

                    result.put("userId",user.getId());


                }
            }
        }else {
            result.put("errorInfo","验证码错误");
            result.put("errorCode","-2");
        }
        return result;
    }

    public static Map modifyPhone( Integer userId,String phone,String smsMessageSid,String smsCode){
        Map result = new HashMap();
        result.put("errorInfo","修改成功");
        result.put("errorCode","0");
        final Date date = new Date();

        List<MessageLogs> list = MessageLogs.dao.find("SELECT * FROM message_logs WHERE sms_message_sid = ?",smsMessageSid);
        if(list != null && list.size() != 0){
            MessageLogs log = list.get(0);
            if("-1".equals(log.getSTATUS())){
                result.put("errorInfo","验证码已使用");
                result.put("errorCode","-1");
            }
            if(!log.getCODE().equals(smsCode)){
                result.put("errorInfo","验证码错误");
                result.put("errorCode","-2");
            }else if(!log.getPHONE().equals(phone)){
                result.put("errorInfo","电话号码不匹配");
                result.put("errorCode","-3");
            }else if(new Date().getTime() - Long.valueOf(log.getCreateTime()) > 1000*60*5){
                result.put("errorInfo","验证码超时");
                result.put("errorCode","-4");
            }else {
                log.setSTATUS("-1").update();
                List<User> users = User.dao.find("SELECT * FROM user where phone = ?",phone);
                if(users != null && users.size() != 0){
                    result.put("errorInfo","用户已存在");
                    result.put("errorCode","-5");
                }else {
                    User.dao.findById(userId).setPhone(phone).update();
                }
            }
        }else {
            result.put("errorInfo","验证码错误");
            result.put("errorCode","-2");
        }
        return result;
    }

    public static Map modifyPwd(Integer userId,String old,String newPassword){
        Map result = new HashMap();
        result.put("errorInfo","修改成功");
        result.put("errorCode","0");
        UserPwd pwd = UserPwd.dao.findFirst("SELECT * FROM user_pwd WHERE user_id = ? ORDER BY create_time DESC ",userId);
        if(pwd != null){
            if(pwd.getPassword().equals(old)){
                new UserPwd().setCreateTime(new Date()).setPassword(newPassword).setUserId(userId).save();
            }else {
                result.put("errorInfo","旧密码错误");
                result.put("errorCode","-1");
            }
        }else {
            new UserPwd().setCreateTime(new Date()).setPassword(newPassword).setUserId(userId).save();
        }
        return result;
    }

    public static void resetPwd(Integer userId){
        new UserPwd().setCreateTime(new Date()).setPassword("123456").setUserId(userId).save();
    }

    public static User userDetail(Integer userId){
        User user = User.dao.findFirst("SELECT\n" +
                "  u.id,\n" +
                "  u.name,\n" +
                "  u.status,\n" +
                "  u.phone,\n" +
                "  u.create_time,\n" +
                "  uei.last_buy_time,\n" +
                "  uei.last_login_time,\n" +
                "  uei.total_order_cnt,\n" +
                "  uei.total_order_price FROM user u, user_ext_info uei\n" +
                "WHERE u.id = uei.user_id and u.id = ?",userId);
        return user;
    }

    public static Map<String,Object> getSmsCode(String phone){
        SmsCode smsCode = new SmsCode(phone);
        return connectSmsAPI(phone,smsCode.getSmsCode());
    }

    private static Map<String,Object> connectSmsAPI(String mobile, String smsCode){
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
        HashMap<String, Object> result = null;
        restAPI.init("app.cloopen.com", "8883");
        restAPI.setAccount("8a48b5514b35422d014b36742f0c00b3", "729f9bd1d95e487085e42a18b8bc1ee9");
        restAPI.setAppId("8aaf07085aabcbbd015acfdff3e40b80");
        if(mobile.equals("18649806115")){
            smsCode = "888888";
        }
        result = restAPI.sendTemplateSMS(mobile,"160262" ,new String[]{smsCode,"5"});

        MessageLogs message = new MessageLogs();
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            message = new MessageLogs();
            message.setPHONE(mobile);
            message.setCODE(smsCode);
            message.setCreateTime(new Date().getTime()+"");
            message.setTimeUnit(5);
            message.setSTATUS(result.get("statusCode").toString());
            Map<String, Object> dataMap= (Map<String, Object>) result.get("data");
            message.setSmsMessageSid(((Map<String, Object>)dataMap.get("templateSMS")).get("smsMessageSid").toString());
            message.save();
            return (Map<String, Object>) result.get("data");
        }else{
            //异常返回输出错误码和错误信息
            result.put("errorInfo","错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
        }
        return result;
    }

    public static User getUserInfo(Integer userId){
        User user = User.dao.findFirst("SELECT u.id,u.phone,u.name,ui.url FROM user u LEFT JOIN user_img ui ON ui.user_id = u.id AND ui.status = 1 WHERE u.id = ?",userId);

        return user;
    }

    public static void updateStatus(Integer userId){
        User user = User.dao.findById(userId);
        user.setStatus("1".equals(user.getStatus()) ? "0" :"1").update();
    }
}
